package com.learn.framework.annotation;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.validation.FieldError;
import org.springframework.validation.BindException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Aspect
@Component
public class FormValidateResponseImpl {
    private static final Logger logger = LoggerFactory.getLogger("FormValidateResponse");
    private Map<String, Integer> redisTemplate=new HashMap<>();
    @Pointcut("@annotation(com.learn.framework.annotation.FormValidateResponse)")
    public void pointcut(){

    }

    @Before("pointcut() && @annotation(formValidateResponse)")
    public void requestLimit(final JoinPoint joinPoint, FormValidateResponse formValidateResponse) {
        System.out.println(joinPoint.getTarget());
    }

    @AfterThrowing(value = "pointcut() && @annotation(formValidateResponse)", throwing = "ex")
    public StringBuffer afterThrowing(final JoinPoint joinPoint, FormValidateResponse formValidateResponse, BindException ex) {
        System.out.println("++++执行了afterThrowing方法++++");
        System.out.println("请求：" + formValidateResponse.toString() + " 出现异常");
        List<FieldError> errors =  ex.getFieldErrors();
        StringBuffer strb = new StringBuffer("");
        if(errors != null && errors.size() > 0){
            for(FieldError error : errors){
                strb.append(error.getDefaultMessage());
                strb.append("\r\n");
            }
        }
        return strb;
    }
}
